/*
*参考链接：http://javacheng.oschina.io/socket.io/get-started/chat/
*/
var express=require('express');
var app= express();
var http= require('http').Server(app);
var io=require('socket.io')(http);

// Routing
app.use(express.static(__dirname + '/'));

// app.get('/',function(req,res){
// 	//res.send('<h1>hello socket.io</h1>')
// 	res.sendFile(__dirname+'/index.html')
// })
http.listen(3000,function(){
	console.log('listening on *:3000');
});


var numUsers = 0;//用户数量
io.on('connection',function(socket){
	var addedUser=false;
	console.log('a user connected');
	//1.当用户连接或断开连接时，广播消息
	// socket.broadcast.emit('other user','hi');//新用户，出发消息

	// socket.on('disconnect',function(){
	//  	console.log('user disconnected');
	//  	socket.broadcast.emit('other user','bye-bye');
	// })



	//将事件发送给每个用户
	// socket.on('chat message',function(msg){
	// 	console.log("message:"+msg);
	// 	io.emit('chat message',msg);
	// });


	//添加用户
	socket.on('add user',function(username){
		if(addedUser){return;}
		socket.username=username;
		++numUsers;
		addedUser=true;
		//用户登录
		socket.emit('login',{
			numUsers:numUsers
		});
		//其他用户加入
		socket.broadcast.emit('user joined',{
			username:socket.username,
			numUsers:numUsers
		})
	})
	//用户输入
	socket.on('typing', function () {
		socket.broadcast.emit('typing', {
			username: socket.username
		});
	});
	//用户停止输入
	socket.on('stop typing', function () {
		socket.broadcast.emit('stop typing', {
			username: socket.username
		});
	});
	//接收消息
	socket.on('new message',function(data){
		socket.broadcast.emit('new message',{
			username:socket.username,
			message:data
		});
	})

	//断开连接
	socket.on('disconnect',function(){
		if(addedUser) {
			--numUsers;
			socket.broadcast.emit('user left', {
				username: socket.username,
				numUsers: numUsers
			});
		}
	});


})